package com.atwisdom.star.service.planning;

import com.alibaba.fastjson2.JSONArray;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Panhao
 * @ClassName Routing
 * @description TODO
 * @date 2024/6/4
 * lastUpdate Panhao
 */
@Data
public class Routing {
    private List<WorkCenter> routing = new ArrayList<WorkCenter>();
    private Set<String> prevIds = new HashSet<String>();

    private void addWorkCenter(WorkCenter workCenter){
        routing.add(workCenter);
    };
    public void setRouting(JSONArray nodes){
        createRouting(nodes);
        setType();
    }
    private void createRouting(JSONArray nodes){
        for(int i = 0; i < nodes.size(); i++){
            String nodeId = nodes.getJSONObject(i).getString("nodeId");
            if(!nodeId.equals("_root")){
                WorkCenter workCenter = new WorkCenter();
                workCenter.setId(nodeId);
                workCenter.setPrev(nodes.getJSONObject(i).getJSONArray("prev").toList(String.class));
                prevIds.addAll(nodes.getJSONObject(i).getJSONArray("prev").toList(String.class));
                String productId = nodes.getJSONObject(i).getString("productId");
                if(productId != null){
                    Product product = new Product(productId);
                }
                addWorkCenter(workCenter);
            }
        }
    }
    private void setType(){
        for(WorkCenter workcenter: routing){
            if(prevIds.contains(workcenter.getId())){
                workcenter.getProduct().setType("semi");
            }else{
                workcenter.getProduct().setType("final");
            }
        }
    }
    public List<WorkCenter> getFinal(){
        return routing.stream().filter(wc -> wc.getProduct().getType().equals("final"))
                .collect(Collectors.toList());
    }
    public List<WorkCenter> getOther(){
        return routing.stream().filter(wc ->!wc.getProduct().getType().equals("final"))
                .collect(Collectors.toList());
    }

    public WorkCenter find(String id){
        return routing.stream().filter(wc ->wc.getId().equals(id))
                .findFirst()
                .get();
    }
    public List<WorkCenter> find(List<String> ids){
        return routing.stream().filter(wc ->ids.contains(wc.getId()))
                .collect(Collectors.toList());
    }
}
